package com.sfj.system.controller;

import com.kaka.starter.control.dto.ResultBean;
import com.sfj.system.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author kaka
 * @Date 2024/04/23
 */
@Api(tags = "附件上传下载")
@RestController
@RequestMapping("file")
public class FileUploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 附件上传
     *
     * @param uploadFile
     * @param @RequestParam
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "附件上传", notes = "附件上传")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public ResultBean uploadFile(@RequestParam("file") MultipartFile uploadFile,
                                 @RequestParam("type") String type) throws IOException {
        return new ResultBean(uploadService.uploadFile(uploadFile, type));
    }

    @GetMapping("/download")
    @ApiOperation(value = "附件下载", notes = "附件下载")
    public void downloadFile(HttpServletResponse response,@RequestParam("filePath") String filePath) throws IOException {
        File file = uploadService.download(filePath);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("File not found: " + file.getAbsolutePath());
            return;
        }

        FileInputStream fis = new FileInputStream(file);

        response.setContentType("application/octet-stream");
        String fileName = file.getName();
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        os.flush();
        os.close();
        fis.close();
    }
}
